document.addEventListener('DOMContentLoaded', () => {
  let currentRecordId = null;
  
  // 初始化标签页
  document.querySelectorAll('.tab').forEach(tab => {
    tab.addEventListener('click', () => {
      document.querySelectorAll('.tab, .tab-content').forEach(el => 
        el.classList.remove('active'));
      tab.classList.add('active');
      document.getElementById(tab.dataset.tab).classList.add('active');
    });
  });

  // 加载日志记录
  function loadLogs() {
    chrome.storage.local.get(['tradeLogs'], ({ tradeLogs = [] }) => {
      // 反转数组实现最新记录在上方
      const reversedLogs = tradeLogs.slice().reverse();
      
      const logList = document.getElementById('logList');
      logList.innerHTML = reversedLogs.map(log => `
        <div class="log-item" data-id="${log.id}">
          <div class="log-content">
            [${new Date(log.timestamp).toLocaleString()}] 
            ${log.type === 'open' ? '开仓' : '平仓'} - 
            品种：${log.symbol} | 方向：${log.direction}<br>
            止损：${log.stopLoss} | 盈亏：${log.profitLoss}
            ${log.screenshot ? `<br><a href="${log.screenshot}" target="_blank">查看截图</a>` : ''}
          </div>
          <div class="log-actions">
            <i class="fas fa-edit edit-btn"></i>
            <i class="fas fa-trash delete-btn"></i>
          </div>
        </div>
      `).join('');

      document.querySelectorAll('.log-item').forEach(item => {
        item.addEventListener('click', (e) => {
          if(e.target.classList.contains('delete-btn')) return;
          
          const id = item.dataset.id;
          chrome.storage.local.get(['tradeLogs'], ({ tradeLogs }) => {
            const record = tradeLogs.find(log => log.id === id);
            if (record) {
              currentRecordId = id;
              // 自动切换到对应标签页
              document.querySelector(`[data-tab="${record.type === 'open' ? 'open' : 'close'}"]`).click();
              // 填充表单
              document.getElementById('symbol').value = record.symbol;
              document.getElementById('direction').value = record.direction;
              document.getElementById('driveLevel').value = record.driveLevel;
              document.getElementById('maLevel').value = record.maLevel;
              document.getElementById('openPrice').value = record.openPrice;
              document.getElementById('stopLoss').value = record.stopLoss;
              document.getElementById('positionValue').value = record.positionValue;
              document.getElementById('totalAccount').value = record.totalAccount;
              document.getElementById('profitLoss').value = record.profitLoss;
              document.getElementById('evaluation').value = record.evaluation;
              document.getElementById('screenshot').value = record.screenshot;
              document.getElementById('summary').value = record.summary;
            }
          });
        });
      });

      // 将删除事件监听移到此处
      document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
          e.stopPropagation();
          const id = btn.closest('.log-item').dataset.id;
          chrome.storage.local.get(['tradeLogs'], ({ tradeLogs }) => {
            const newLogs = tradeLogs.filter(log => log.id !== id);
            chrome.storage.local.set({ tradeLogs: newLogs }, loadLogs);
          });
        });
      });
    });
  }

  // 保存记录
  document.getElementById('saveBtn').addEventListener('click', () => {
    const activeTab = document.querySelector('.tab.active').dataset.tab;
    const record = {
      id: currentRecordId || Date.now().toString(),
      // 交易分析字段
      symbol: document.getElementById('symbol').value,
      direction: document.getElementById('direction').value,
      driveLevel: document.getElementById('driveLevel').value,
      maLevel: document.getElementById('maLevel').value,
      
      // 开仓字段
      openPrice: document.getElementById('openPrice').value,
      stopLoss: document.getElementById('stopLoss').value,
      positionValue: document.getElementById('positionValue').value,
      totalAccount: document.getElementById('totalAccount').value,
      
      // 平仓字段
      profitLoss: document.getElementById('profitLoss').value,
      evaluation: document.getElementById('evaluation').value,
      screenshot: document.getElementById('screenshot').value,
      summary: document.getElementById('summary').value,
      
      timestamp: Date.now(),
      type: activeTab === 'open' ? 'open' : 'close'
    };

    chrome.storage.local.get(['tradeLogs'], ({ tradeLogs = [] }) => {
      const index = tradeLogs.findIndex(log => log.id === record.id);
      if (index > -1) {
        tradeLogs[index] = record;
      } else {
        tradeLogs.push(record);
      }
      chrome.storage.local.set({ tradeLogs }, loadLogs);
    });
  });

  // 导出CSV
  document.getElementById('exportBtn').addEventListener('click', () => {
    chrome.storage.local.get(['tradeLogs'], ({ tradeLogs }) => {
      const csvContent = [
        '时间,类型,品种,方向,推动级别,均线级别,开仓价,止损价,仓位价值,账户总额,盈亏,评价,截图链接,总结',
        ...tradeLogs.map(log => 
          `${new Date(log.timestamp).toLocaleString()},${log.type},${log.symbol},` +
          `${log.direction},${log.driveLevel},${log.maLevel},${log.openPrice},` +
          `${log.stopLoss},${log.positionValue},${log.totalAccount},` +
          `${log.profitLoss},"${log.evaluation}","${log.screenshot}","${log.summary}"`
        )
      ].join('\n');

      const blob = new Blob([csvContent], { type: 'text/csv' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'trade_logs.csv';
      a.click();
    });
  });

  // 添加导入功能
  document.getElementById('importBtn').addEventListener('click', () => {
    document.getElementById('importFile').click();
  });

  document.getElementById('importFile').addEventListener('change', (e) => {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (event) => {
      const csvData = event.target.result;
      const rows = csvData.split('\n').slice(1); // 跳过标题行
      
      const importedLogs = rows.map(row => {
        const [
          timestamp, type, symbol, direction, driveLevel, maLevel, 
          openPrice, stopLoss, positionValue, totalAccount, 
          profitLoss, evaluation, screenshot, summary
        ] = row.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/); // 处理带引号的字段

        return {
          id: Date.now().toString(), // 生成新ID避免冲突
          timestamp: new Date(timestamp).getTime(),
          type,
          symbol,
          direction,
          driveLevel,
          maLevel: parseInt(maLevel),
          openPrice: parseFloat(openPrice),
          stopLoss: parseFloat(stopLoss),
          positionValue: parseFloat(positionValue),
          totalAccount: parseFloat(totalAccount),
          profitLoss: parseFloat(profitLoss),
          evaluation: evaluation.replace(/^"|"$/g, ''),
          screenshot: screenshot.replace(/^"|"$/g, ''),
          summary: summary.replace(/^"|"$/g, '')
        };
      }).filter(log => log.symbol); // 过滤空行

      chrome.storage.local.get(['tradeLogs'], ({ tradeLogs = [] }) => {
        const mergedLogs = [...tradeLogs, ...importedLogs];
        chrome.storage.local.set({ tradeLogs: mergedLogs }, () => {
          alert(`成功导入 ${importedLogs.length} 条记录`);
          loadLogs();
        });
      });
    };
    reader.readAsText(file);
  });

  // 加载初始数据
  loadLogs();
}); 